<?php

declare(strict_types=1);

namespace app\yperp\command;

use DateTime;
use Facebook\WebDriver\Exception\NoSuchWindowException;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Fastposter\Client as FastposterClient;
use think\console\Command;
use think\console\Input;

use think\console\Output;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\LimitStream;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Stream;
use InvalidArgumentException;
use RuntimeException;
use think\Db;
use think\facade\Cache;

class suosi extends Command
{

    protected $output;

    protected $input;
    protected $driver;
    protected $windows = [];
    protected $cookies = [];

    protected $token = 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2luZm8iOiIlN0IlMjJhdmF0YXIlMjIlM0ElMjJodHRwcyUzQSUyRiUyRndld29yay5xcGljLmNuJTJGd3dwaWMzYXolMkY5OTU3ODZfTnc0YXFZZEZTamFHbmpVXzE3MTYyNzc3MzMlMkYwJTIyJTJDJTIyY29ycElkJTIyJTNBJTIyd3cyYjFhOGVkZGIzMjcyZmZiJTIyJTJDJTIyaW5kdXN0cnlUeXBlJTIyJTNBJTIybXl0eGwlMjIlMkMlMjJsb2dpblR5cGUlMjIlM0ElMjJub3JtYWwlMjIlMkMlMjJtZW1iZXJJZCUyMiUzQTE3NjA5Mjg5MjA1MjY1ODAxMTMlMkMlMjJtZW1iZXJOYW1lJTIyJTNBJTIyJUU2JTlEJThFJUU0JUI4JTk2JUU1JUI5JUIzJTIyJTJDJTIybW9iaWxlJTIyJTNBJTIyMTg5ODExNDAxMDElMjIlMkMlMjJvcmdJZCUyMiUzQTEwMDAxMCUyQyUyMm9yZ05hbWUlMjIlM0ElMjIlRTklOTUlQkYlRTglOTklQjklRUYlQkMlODglRTYlOTklQkElRTYlOTglOTMlRTUlQUUlQjYlRUYlQkMlODklMjIlMkMlMjJvcmdUeXBlJTIyJTNBJTIyZ2VuZXJhbCUyMiUyQyUyMnJlZ2lvbkNvZGUlMjIlM0ElMjIwMDAwMDAwMDAwMDAwMDAwMDAlMjIlMkMlMjJzaG9ydE5hbWUlMjIlM0ElMjIlRTYlOTklQkElRTYlOTglOTMlRTUlQUUlQjYlMjIlMkMlMjJ1c2VySWQlMjIlM0ExNzYwOTI4OTIwNTI2NTgwMTEzJTJDJTIydXNlck5hbWUlMjIlM0ElMjIlRTYlOUQlOEUlRTQlQjglOTYlRTUlQjklQjMlMjIlMkMlMjJ1c2VyVHlwZSUyMiUzQSUyMmVtcGxveWVlJTIyJTdEIiwidXNlcl9uYW1lIjoiMTAwMDEwOzE3NjA5Mjg5MjA1MjY1ODAxMTM7ZW1wbG95ZWU7bm9ybWFsIiwib3JnX2lkIjoxMDAwMTAsInNjb3BlIjpbImFsbCJdLCJleHAiOjE3MjQzNzY1MzYsImp0aSI6IjBjZTlhNmQ3LWIwNDgtNDlmZS05YjkwLTljOWM3YzlhODNlNCIsImNsaWVudF9pZCI6InByb2R1Y3Rpb24ifQ.oELIeFt774ZgV-NDlJarV3uC4iOM9tyc7OVeL_cHUSL6eQpQP5Xxpqns_CWuBLfRaimxrR6PLw-YRb421HIxc71z5UoEXaLTjANN0ly4EMwLpbR6IYyg02w6cetYg4lSwM4K98j0QmW5u3K-L2_YK5LwJZAP-XfapfUBwSNrh6A';

    protected function configure()
    {
        // 指令配置
        $this->setName('suosi')
            ->setDescription('生成个人活码');
    }
    public $grpup_ids = [
        '合肥' => '1793134835194183681',
        '成都' => '1781208814111330306',
        '绵阳' => '1780805443831369730',
        '重庆' => '1773036129085140994',
        '虹创' => '1763096116967170050',
        '测试' => '1760952172240629761'
    ];

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $this->input = $input;

        $this->output = $output;

        try {
            $this->create();
            // $this->update();
        } catch (\Throwable $th) {
            dump($th->getMessage());
            dump($th->getTraceAsString());
        }

    }

    function update($type = '绵阳')
    {
        $users = $this->get_staff_qr_list($this->grpup_ids[$type]);

        foreach ($users as $key => $staff) {
            if ($key < 40) {
                continue;
            }
            $user = Db::table('dp_suosi_user')
                ->where('username', $staff['name'])
                // ->where('preson_qr_status', 0)
                // ->limit(1)
                ->find();
            if ($user) {


                // dump([$staff['name'], $user]);
                $params = [
                    'id' => $staff['id'],
                    'name' => $user['username'],
                    'groupId' => $this->grpup_ids[$user['dep']],
                    'check_dept' => $user['dep'] . '分部' . $user['dep_type'] . '导购员',
                    // 'check_dept' =>   '导购员',
                    'shopname' => $user['dep_name'],
                    'dept_type' => $user['dep'] . $user['dep_type'] . '中心'
                ];
                dump(['update-$params' => $params]);
                $data = $this->update_preson_qr($params);
                dump(['update-response' => $data]);
                if ($data['success']) {
                    $user = Db::table('dp_suosi_user')->where($user)->update(['preson_qr_status' => 1]);
                    dump($user);
                } else {
                    $user = Db::table('dp_suosi_user')->where($user)->update(['preson_qr_status' => 0, 'preson_qr' => json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)]);
                    dump($user);
                }
            }
        }
    }

    /**
     * 获取员工活码列表
     */


    function create()
    {
        // $hskIdList = $this->search_msg_tmpl_ids('君果');
        // dump($hskIdList);
        // die;
        $users = Db::table('dp_suosi_user')
            // ->where('username', '陈秀梅')
            // ->where('preson_qr_status', 0)
            // ->limit(1)
            ->select();
        foreach ($users as $key => $user) {
            $params = [
                'name' => $user['username'],
                'groupId' => $this->grpup_ids[$user['dep']],
                'check_dept' => $user['dep'] . '分部' . $user['dep_type'] . '导购员',
                // 'check_dept' =>   '导购员',
                'shopname' => $user['dep_name'],
                'dept_type' => $user['dep'] . $user['dep_type'] . '中心'
            ];
            dump(['create' => $params]);
            $data = $this->save_preson_qr($params);
            dump($data);
            if ($data['success']) {
                $user = Db::table('dp_suosi_user')->where($user)->update(['preson_qr_status' => 1]);
                dump($user);
            } else {
                $user = Db::table('dp_suosi_user')->where($user)->update(['preson_qr_status' => 0, 'preson_qr' => json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)]);
                dump($user);
            }
        }
    }
    function require($url = '', $json, $method = 'POST')
    {
        $client = new Client(['verify' => env('root_path') . 'application\yperp\common\cacert.pem',]);
        $headers = [
            'authorization' => $this->token,
            'content-type' => 'application/json;charset=utf-8'
        ];
        $body = json_encode($json);
        $request = new Request($method, $url, $headers, $body);
        $res = $client->sendAsync($request)->wait();
        $res = $res->getBody()->getContents();
        return json_decode($res, true);
    }
    function get_staff_qr_list($group_id)
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/staff/page';
        $response = $this->require($url, [
            "groupId" => $group_id,
            "search" => (object) [],
            // "search" => (object) ['keyword' => "杨利娟"],
            "pageNo" => 1,
            "pageSize" => 300,
        ]);
        return $response['data']['dataSource'];
    }

    public function method_user_search($keyword = '李世平', $check_dept = '')
    {
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/search';
        $params = ['keyword' => $keyword, 'types' => ['innerContacts'], 'selectTypeList' => ['user_and_dept']];
        $data = $this->require($url, $params);
        $response = [];
        $response_data = [];
        if (count($data['data']['dataSource']) > 0) {
            $data = $data['data']['dataSource'];
            foreach ($data as $key => $values) {
                foreach ($values['userDeptList'] as $k => $item) {
                    // dump([$item['deptName'], $check_dept]);
                    if ($this->similar($item['deptName'], $check_dept) > 50) {

                        $response_data = $values;
                    }
                }
            }
        }
        if (!empty($response_data)) {
            $response = [
                "id" => $response_data['key'],
                "key" => $response_data['key'],
                "name" => $response_data['label'],
                "type" => "USER",
                "orgId" => 100010,
                "contactType" => 1,
                "childDelete" => true
            ];
        }

        return $response;


    }

    public function method_tag_search($keyword = '杜明虹', $check_dept = '分部客户资产')
    {
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/search';
        $param = ['keyword' => $keyword, 'types' => ['customerTagContacts'], 'selectTypeList' => ['tag']];
        $response = $this->require($url, $param);

        $response_data = [];
        if (count($response['data']['dataSource']) > 0) {

            $dataSource = $response['data']['dataSource'];
            $dataSource_find = [];
            foreach ($dataSource as $key => $value) {
                if ($value['labelPathName'] !== $check_dept) {
                    continue;
                }
                if ($value['label'] == $keyword) {
                    $dataSource_find = $value;
                }
            }
            if (!empty($dataSource_find)) {
                $response_data = [
                    'id' => $dataSource_find['key'],
                    'key' => $dataSource_find['key'],
                    'name' => $dataSource_find['label'],
                    'type' => 'CUSTOMER_TAG',
                    'orgId' => '100010',
                    'contactType' => 9,
                    'childDelete' => true
                ];
            }

        }
        return $response_data;

    }


    public function method_tag_create($customerTagInfoList = [], $check_dept = '')
    {
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/result';
        $data = [
            'selectTypeList' => ['tag'],
            'tagTypeList' => [1],
            'labelPermission' => 1,
            'deptInfoList' => [],
            'userInfoList' => [],
            'groupInfoList' => [],
            'tagInfoList' => [],
            'customerTagInfoList' => $customerTagInfoList,
            'types' => ['customerTagContacts'],
            'weChatTagInfoList' => [],
            'customerManagerInfoList' => [],
            'managerUserInfoList' => [],
            'managerGroupInfoList' => [],
            'employeeCodeInfoList' => [],
            'groupTagInfoList' => [],
            'circlesTagInfoList' => [],
            'contentTagInfoList' => [],
            'equipmentInfoList' => [],
            'tvInfoList' => [],
            'maternalInfoList' => [],
            'cameraInfoList' => [],
            'workGroupInfoList' => [],
            'id' => '100010-' . $this->create_time_str(),
        ];

        // dump($data);die;
        $data = $this->require($url, $data);
        return $data;

    }

    function save_preson_qr($params = [])
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/staff/save';

        // $userDeptList = $this->method_user_search('李世平', $params['check_dept']);
        $labelSignature = $this->method_tag_create([
            $this->method_tag_search($params['shopname']),//'广元美天美电器有限公司'
            $this->method_tag_search($params['name']),//杜明虹
            $this->method_tag_search($params['dept_type']), //绵阳冰洗中心
        ]);

        $param = [
            'name' => $params['name'],
            'groupId' => $params['groupId'],
            'statFlagIdList' => [],
            'skipVerify' => 0,
            'userDeptList' => [
                [
                    "id" => "1760928920526579225",
                    "name" => "李世平",
                    "type" => "USER"
                ]
            ],
            'labelSignature' => $labelSignature['data'],
            'hskBean' => ['welcomeType' => 1],
        ];
        dump(['save_preson_qr' => $param]);
        // return $param;
        $response = $this->require($url, $param);
        return $response;
    }

    function update_preson_qr($params = [])
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/staff/update';

        // $userDeptList = $this->method_user_search('李世平', $params['check_dept']);
        $labelSignature = $this->method_tag_create([
            $this->method_tag_search($params['shopname']),//'广元美天美电器有限公司'
            $this->method_tag_search($params['name']),//杜明虹
            $this->method_tag_search($params['dept_type']), //绵阳冰洗中心
        ]);
        $hskIdList = $this->search_msg_tmpl_ids($params['shopname']);
        $param = [
            'id' => $params['id'],
            'name' => $params['name'],
            'groupId' => $params['groupId'],
            'statFlagIdList' => [],
            'skipVerify' => 0,
            'userDeptList' => [
                [
                    "id" => "1760928920526579225",
                    "name" => "李世平",
                    "type" => "USER"
                ]
            ],
            'labelSignature' => $labelSignature['data'],
            'hskBean' => [
                'welcomeType' => 1,
                "welcomeContent" => "[curreceiver] 宝贝你终于来啦！以后我就是你的家电顾问啦！以后输入数字0，就可以接入我们在线客服啦！ 长按扫码加入下方门店群每周都有福利等你哦！虹包雨、家电使用技巧等不要错过哦!",
                "hskIdList" => [
                    $hskIdList
                ]
            ],
            'remark' => '',

        ];
        dump(['update_preson_qr' => $param]);
        // return $param;
        $response = $this->require($url, $param);
        return $response;
    }
    function search_msg_tmpl_ids($keyword)
    {
        $url = 'https://m.suosishequ.com/gateway/hsk/web/hs/page';
        $param = [
            "appCode" => "hsk",
            "search" => ["keyword" => $keyword, "newsTypes" => "3"],
            "newsTypes" => ["3"],
            "pageNo" => 1,
            "pageSize" => 20
        ];
        dump(['search_msg_tmpl_ids_$param' => $param]);
        $response = $this->require($url, $param);
        return $response['data']['dataSource'][0]['id'];

    }


    function create_time_str()
    {

        // 获取当前时间
        $date = new DateTime();
        $microseconds = sprintf("%06d", ($date->format("u")));

        // 格式化时间值
        $time_value = $date->format("YmdHis") . $microseconds;

        return $time_value;

    }


    function similar($string1, $string2)
    {
        similar_text($string1, $string2, $percent);
        return (int) $percent;
    }
}
